﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Transactions;

/// <summary>
/// Summary description for BankService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class BankService : System.Web.Services.WebService {

    ShopDataContext db = new ShopDataContext();

    public BankService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    
    [WebMethod]
    public AccountBank Validate(string accNumber, string pin) 
    {

        AccountBank accBank = (from acc in db.AccountBanks
                    where acc.aAccountNumber == accNumber
                    where acc.aAccountPIN == pin
                    where acc.aActive == true
                    select acc).FirstOrDefault();

        return accBank;
    }

    [WebMethod]
    public bool Transfer(string fromAccNumber, string toAccNumber, int amount)
    {
        bool result = false;

        using (TransactionScope scope = new TransactionScope())
        {
            AccountBank from = (from acc in db.AccountBanks
                               where acc.aAccountNumber == fromAccNumber
                               select acc).FirstOrDefault();
            AccountBank to = (from acc in db.AccountBanks
                              where acc.aAccountNumber == toAccNumber
                              select acc).FirstOrDefault();

            if (from.aBalance > amount)
            {
                from.aBalance -= amount;

                to.aBalance += amount;

                db.SubmitChanges();

                scope.Complete();

                result = true;
            }
        }

        return result;
    }
}
